package com.monkey.im.core;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

/**
 * 系统内核
 * @author: yb
 * @date: 2025/4/19 0019 22:15
 */
public final class Kernel {
    private static GenericApplicationContext applicationContext = null;

    private Kernel() {}

    /**
     * 运行环境上下文环境对象获取
     * @return
     */
    public static ApplicationContext getInstance() {
        return applicationContext;
    }

    public static GenericApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取Bean
     * @param name
     * @return
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    /**
     * 获取Bean
     * @param name
     * @param requiredType
     * @return
     * @param <T>
     * @throws BeansException
     */
    public static <T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException {
        return applicationContext.getBean(name, requiredType);
    }

    /**
     * 获取Bean
     * @param name
     * @param args
     * @return
     * @throws BeansException
     */
    public static Object getBean(String name, Object... args) throws BeansException {
        return applicationContext.getBean(name, args);
    }

    /**
     * 获取Bean
     * @param requiredType
     * @param args
     * @return
     * @param <T>
     * @throws BeansException
     */
    public static <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
        return applicationContext.getBean(requiredType, args);
    }

    /**
     * 获取Bean
     * @param requiredType
     * @return
     * @param <T>
     * @throws BeansException
     */
    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        return applicationContext.getBean(requiredType);
    }

    /**
     * 退出系统
     * @param exitCodeGenerators
     * @return
     */
    public static int exit(ExitCodeGenerator... exitCodeGenerators) {
        int exit = SpringApplication.exit(applicationContext, exitCodeGenerators);
        System.exit(exit);
        return exit;
    }

    /**
     * BeanPostProcessor 为了提前初始化_ApplicationContextListener
     */
    @Component
    static class MyApplicationContextListener implements BeanPostProcessor {
        public MyApplicationContextListener(GenericApplicationContext context) {
            Kernel.applicationContext = context;
        }
    }
}
